﻿using System.ComponentModel.Composition;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using easytodoservice.Infrastructure;
using easytodoservice.Model;
using Microsoft.ApplicationServer.Http;
using Microsoft.ApplicationServer.Http.Dispatcher;

namespace easytodoservice.Resources
{
    [ServiceContract]
    [Export]
    public class NoteResource
    {
        private readonly INoteRepository _repository;

        [ImportingConstructor]
        public NoteResource(INoteRepository repository)
        {
            _repository = repository;
        }

        [WebGet(UriTemplate = "{id}")]
        public HttpResponseMessage<Note> Get(int id)
        {
            var note = _repository.Get(id);

            var noteResponse = new HttpResponseMessage<Note>(note);
            return noteResponse;
        }

        [WebInvoke(Method = "POST", UriTemplate = "")]
        public HttpResponseMessage<Note> Post(Note note)
        {

            if (note == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            _repository.Post(note);

            var response = new HttpResponseMessage<Note>(note) {StatusCode = HttpStatusCode.Created};
            return response;
        }

        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
        public HttpResponseMessage<Note> Put(int id, Note note)
        {
            _repository.Get(id);
            _repository.Update(note);

            var response = new HttpResponseMessage<Note>(note);
            return response;
        }

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        public HttpResponseMessage<Note> Delete(int id)
        {
            var deleted = _repository.Get(id);
            _repository.Delete(id);

            var response = new HttpResponseMessage<Note>(deleted);
            return response;
        }

    }
}